import HModal from "@/components/ant-ext/HModal";
import {useTableActionRedux} from "@/components/ant-ext-table/redux/HAdminContext";
import {Form} from "antd";
import HFormItem from "@/components/ant-ext/HFormItem";
import {Stat} from "@/const/const";
import SysRole, {SysRoleEntity} from "@/api/sys-role";
import {useActionForm} from "@/common/hooks";
import SysOrg from "@/api/sys-org";
import {useEffect, useState} from "react";


export default function RoleEdit() {
    const [loading, setLoading] = useState(false)
    const {action, reset} = useTableActionRedux<SysRoleEntity>()
    const {form, key, title} = useActionForm(action, [SysRole.EDIT], SysRole.MAPPING)
    const close = () => {
        reset()
        form.resetFields()
    }
    useEffect(() => {
        if (action.match(SysRole.EDIT)) {
            SysRole.selectById({
                params: {code: action.getRow()?.roleCode}, setLoading, success: (data) => {
                    form.setFieldsValue(data)
                }
            })
        }
    }, [action, form])


    return <>

        <HModal onCancel={close} type={"setUp"} style={{width: "400px", height: "200px"}} confirmLoading={loading}
                onOk={form.submit}
                visible={title !== undefined}
                title={title}
        >
            <Form name={"editForm"} form={form} labelCol={{sm: 6}} onFinish={() => {
                SysRole.doEdit({
                    body: {...form.getFieldsValue(), add: key === SysRole.ADD}, setLoading, success: () => {
                        close()
                    }
                })
            }}>
                <HFormItem label={"角色编码"} name={"roleCode"} required disabled={key !== SysRole.ADD}/>
                <HFormItem label={"角色名称"} name={"roleName"} required/>
                <HFormItem label={"隶属组织"} name={"orgCode"} type={"treeSelect"} dataSource={SysOrg.selectTree} required/>
                <HFormItem label={"状态"} type={"radio"} dataSource={Stat.select} name={"stat"} required/>

            </Form>
        </HModal>
    </>
}